from flask import Blueprint, render_template, redirect, url_for, request, flash
from flask_login import login_user, logout_user, login_required, current_user
from . import user_db
from .models import User

auth_bp = Blueprint('auth', __name__)

@auth_bp.route('/login', methods=['GET', 'POST'])
def login():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        user_data = user_db.verify_user(username, password)
        if user_data:
            user = User(user_data)  # 创建 User 对象
            login_user(user)
            return redirect(url_for('main.index'))
        
        flash('用户名或密码错误')
    return render_template('login.html')

@auth_bp.route('/register', methods=['GET', 'POST'])
def register():
    if request.method == 'POST':
        username = request.form.get('username')
        password = request.form.get('password')
        
        if user_db.create_user(username, password):
            flash('注册成功，请登录')
            return redirect(url_for('auth.login'))
        
        flash('用户名已存在')
    return render_template('register.html')

@auth_bp.route('/logout')
@login_required
def logout():
    logout_user()
    return redirect(url_for('auth.login'))
